package wci.backend.interpreter;

import wci.backend.*;
import wci.backend.interpreter.executors.SelectExecutor;
import wci.backend.interpreter.executors.StatementExecutor;
import wci.intermediate.ICode;
import wci.intermediate.ICodeNode;
import wci.intermediate.SymTab;
import wci.intermediate.SymTabStack;
import wci.message.*;

import static wci.message.MessageType.INTERPRETER_SUMMARY;

/**
 * <h1>Executor</h1>
 *
 * <p>解释器后端执行器</p>
 *
 * <p>Copyright (c) 2009 by Ronald Mak</p>
 * <p>For instructional purposes only.  No warranties.</p>
 */
public class Executor extends Backend
{
	//执行的语句数
	protected static int executionCount = 0;
	//错误处理类
	protected static RuntimeErrorHandler errorHandler = new RuntimeErrorHandler();
	
    public Executor() {
		super();
    }
    //本章的parent继承主要是共享此Executor的两个static域，真无聊的对称！
    public Executor(Executor parent){
    	super();
    }
    public RuntimeErrorHandler getErrorHandler() {
		return errorHandler;
	}
	public void process(ICode iCode, SymTabStack stack)
        throws Exception
    {
		this.iCode = iCode;
		this.symTabStack = stack;
        long startTime = System.currentTimeMillis();
        ICodeNode root_node = this.iCode.getRoot();
        StatementExecutor root_executor = new StatementExecutor(this);
        root_executor.execute(root_node);
        float elapsedTime = (System.currentTimeMillis() - startTime)/1000f;
        int runtimeErrors = errorHandler.getErrorCount();
        // 发送解释摘要消息
        sendMessage(new Message(INTERPRETER_SUMMARY,
                                new Number[] {executionCount,
                                              runtimeErrors,
                                              elapsedTime}));
        //清空缓存，保证垃圾收集
        SelectExecutor.clearCache();
    }
}
